import socket
import threading

def send_input(sock: socket.socket):
    """后台线程：读取用户输入并发送给服务器"""
    while True:
        try:
            text = input()  # 等价于 readln()
            sock.send(text.encode("utf-8"))
        except Exception as e:
            print("发送失败:", e)
            break


def main():
    host = "127.0.0.1"
    port = 8080

    # 创建 TCP 客户端并连接
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, port))
    print("开始聊天")

    # 启动输入线程
    thread = threading.Thread(target=send_input, args=(client,))
    thread.daemon = True  # 后台线程
    thread.start()

    # 主线程：接收来自服务器的消息
    while True:
        try:
            data = client.recv(1024)
            if not data:
                print("服务器已断开")
                break
            print(data.decode("utf-8"))
        except Exception as e:
            print("接收失败:", e)
            break

    client.close()


if __name__ == "__main__":
    main()
